<template>
  <!-- 手动创建订单 -->
  <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="reset" width="1300px">
    <div class="form-box new_form_box">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="80px" class="demo-ruleForm">
        <div style="margin-bottom: 10px;display: flex;align-items: center;">
          <formSubTitVue title="订单信息"></formSubTitVue>
           <el-button @click="fillIn" type="text">快速填充</el-button>
        </div>
        <el-form-item label="游戏名称" prop="gameId">
          <el-select filterable clearable v-model="form.gameId" placeholder="请选择游戏名称" @change="gameChange">
            <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="游戏区服" prop="qufuIds">
          <el-cascader clearable v-model="form.qufuIds" :options="qufuTree" :props="qufuProps" @change="qufuChange"></el-cascader>
        </el-form-item>
        <el-form-item label="游戏账号" prop="accountNumber">
          <el-input v-model="form.accountNumber" placeholder="请输入游戏账号" />
        </el-form-item>
        <el-form-item label="账号密码" prop="accountPassword">
          <el-input v-model="form.accountPassword" placeholder="请输入账号密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="securityPhone">
          <el-input v-show="false" v-model="form.securityPhone" placeholder="请输入手机号" />
          <span class="phone-box flex alc">
            <span class="name" v-if="form.securityPhone">{{ form.securityPhone }}</span>
            <el-button type="text" @click="openSelectPhone">
              选择
            </el-button>
            <el-button style="margin-left: 10px;" v-if="form.securityPhone" type="del" @click="delPhone('phone')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <el-form-item label="回收价" prop="backAmount">
          <el-input v-model="form.backAmount" placeholder="请输入回收价" @change="computedBuyerActualAmount" />
        </el-form-item>
        <el-form-item label="出售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入出售价" />
        </el-form-item>
        <el-form-item label="包赔费" prop="guaranteeAmount">
          <el-input v-model="form.guaranteeAmount" placeholder="请输入包赔费" @change="computedBuyerActualAmount" />
        </el-form-item>
        <!-- <el-form-item label="应付金额" prop="buyerActualAmount">
          <el-input v-model="form.buyerActualAmount" placeholder="请输入应付金额" />
        </el-form-item> -->
        <el-form-item label="回收人" prop="buyerId">
          <el-select filterable clearable v-model="form.buyerId" placeholder="请选择回收人" @change="buyerChange">
            <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
          </el-select>
          <!-- <el-input v-model="form.buyerId" placeholder="请输入回收人" /> -->
        </el-form-item>
        <el-form-item label="包赔商" prop="guaranteeTenantName">

          <el-input v-show="false" v-model="form.guaranteeTenantName" placeholder="请输入" />
          <span class="phone-box flex alc">
            <span class="name" v-if="form.guaranteeTenantName">{{ form.guaranteeTenantName }}</span>
            <el-button type="text" @click="openSelectQudao(1)">
              选择
            </el-button>
            <el-button style="margin-left: 10px;" v-if="form.guaranteeTenantName" type="del" @click="delPhone('guaranteeTenantName')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <el-form-item label="回收渠道" prop="channel">
          <el-input v-show="false" v-model="form.channel" placeholder="请输入" />
          <span class="phone-box flex alc">
            <span class="name" v-if="form.channel">{{ form.channel }}</span>
            <el-button type="text" @click="openSelectQudao(2)">
              选择
            </el-button>
            <el-button style="margin-left: 10px;" v-if="form.channel" type="del" @click="delPhone('channel')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <el-form-item label="三方单号" prop="otherNo">
          <el-input v-model="form.otherNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="号主电话" prop="sellerPhone">
          <el-input v-model="form.sellerPhone" placeholder="请输入号主手机" />
        </el-form-item>
        <el-form-item label="卖家名称" prop="sellerName">
          <el-input v-model="form.sellerName" placeholder="请输入卖家名称" />
        </el-form-item>
        <el-form-item label="支付状态" prop="buyerPayStatus">
          <el-select clearable v-model="form.buyerPayStatus" placeholder="请选择支付状态">
            <el-option label="未支付" :value="1" />
            <el-option label="已支付" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="换绑状态" prop="changeBindState">
          <el-select clearable v-model="form.changeBindState" placeholder="请选择换绑状态">
            <el-option label="未换绑" :value="1" />
            <el-option label="已换绑" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="放款状态" prop="guaranteePayStatus">
          <el-select clearable v-model="form.guaranteePayStatus" placeholder="请选择放款状态">
            <el-option label="未放款" :value="1" />
            <el-option label="已放款" :value="2" />
          </el-select>
        </el-form-item>
        <div v-if="form.buyerActualAmount" style="text-align: right;padding-right: 40px;">
          <span class="font16">应付金额：</span>
          <span style="color: red;font-size: 24px;">{{ form.buyerActualAmount }}</span>
        </div>
        <div style="margin: 10px 0;">
          <formSubTitVue title="财务信息"></formSubTitVue>
        </div>
        <el-form-item label="收款方" prop="shoukuanfang">
          <el-input v-model="form.shoukuanfang" placeholder="请输入收款方" />
        </el-form-item>
        <el-form-item label="收款账号" prop="shoukuanzhanghao">
          <el-input v-model="form.shoukuanzhanghao" placeholder="请输入收款账号" />
        </el-form-item>

        <div style="margin: 10px 0;">
          <formSubTitVue title="其他信息"></formSubTitVue>
        </div>
        <el-form-item label="其他备注" prop="remark" class="row">
          <el-input v-model="form.remark" type="textarea" placeholder="订单其他备注" :rows="4" />
        </el-form-item>
        <el-form-item label="" prop="" class="row">
          <div class="upload_img_box flex">
            <el-form-item label="订单截图" prop="buyerImg">
              <uploadImageOne v-model="form.buyerImg" ></uploadImageOne>
            </el-form-item>
            <el-form-item label="二次实名截图" label-width="110px" prop="secondImg">
              <uploadImageOne v-model="form.secondImg"></uploadImageOne>
            </el-form-item>
            <el-form-item label="钱包截图" prop="walletImg">
              <uploadImageOne v-model="form.walletImg" ></uploadImageOne>
            </el-form-item>
            
          </div>

        </el-form-item>
        <el-form-item label="其他图片" class="row">
          <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="50" :on-remove="handleRemove" :headers="headers">
            <div class="uploadbg">
              <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
              <br />
              <span>上传图片</span>
            </div>
          </el-upload>
          <div style="width: 100px;">
            <saomaUpload @success="saomaEnd">
              <el-button type="primary" plain>扫码上传</el-button>
            </saomaUpload>
          </div>
          <!-- <div style="line-height: 14px;margin-bottom: 10px;">请上传其他需要记录的图片</div> -->
        </el-form-item>
        <div style="margin: 10px 0;">
          <formSubTitVue title="包赔信息"></formSubTitVue>
        </div>
        <el-form-item class="row" label="是否填写" prop="">
          <el-radio-group v-model="isBaopei">
            <el-radio :label="true">填写</el-radio>
            <el-radio :label="false">不填写</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="isBaopei">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入卖家姓名" />
          </el-form-item>
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入卖家身份证号" />
            <!-- <span>年龄： <span :style="{color:`${getUserAge>=18?'#333':'red'}`}">{{getUserAge}}</span></span> -->
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="form.phoneNumber" placeholder="请输入卖家手机号" />
          </el-form-item>

          <el-form-item label="地址" prop="adress">
            <el-input v-model="form.adress" placeholder="请输入卖家地址" />
          </el-form-item>
          <el-form-item class="row" label="其他信息" prop="otherRemark">
            <el-input type="textarea" rows="4" v-model="form.otherRemark" placeholder="请输入其他信息备注" />
          </el-form-item>
          <el-form-item class="row" label-width="100px" label="身份证国徽面" prop="emblemIdcardImg">
            <uploadImageOne v-model="form.emblemIdcardImg" @change="emblemIdcardImgChange"></uploadImageOne>
          </el-form-item>
          <el-form-item class="row" label-width="100px" label="身份证人像面" prop="faceIdcardImg" :class="{ 'hiddenupload': form.faceIdcardImg }">
            <uploadImageOne v-model="form.faceIdcardImg" @change="faceIdcardImgChange"></uploadImageOne>
          </el-form-item>
        </div>

        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
        </div>
      </el-form>
      <!-- 弹出 -->
      <selectPhone ref="selectPhone" @change="getSelectPhone"></selectPhone>
      <!-- 渠道选择 -->
      <qudaoDialog ref="qudaoDialog" @change="getSelectQudao"></qudaoDialog>

      <huishouFillIn ref="huishouFillInRef" @fillData="handleFillData"></huishouFillIn>


    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import jizhangbenApi from "@/api/financeCenter/jizhangben.js";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import gameListApi from "@/api/gameConfig/gameList";
import formSubTitVue from "@/views/tenantPages/components/formSubTit.vue";

import huishouFillIn from "@/layout/components/components/huishouFillIn";


import supplyConfigApi from "@/api/system/supplyConfig";
import selectPhone from "../../goodsList/selectPhone.vue";
import qudaoDialog from "./qudaoDialog.vue";
import saomaUpload from "../../../../components/upload/saomaUpload.vue";
export default {
  name: "",
  components: { formSubTitVue, selectPhone, qudaoDialog, saomaUpload ,huishouFillIn },
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入金额"));
      } else if (!this.priceReg.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    var phoneCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    };
    var idCardRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入身份证号"));
      } else if (!this.idCardReg.test(value)) {
        callback(new Error("请输入正确的身份证号"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,

      currentGame: "",
      gameList: [],
      idcardImg1: [],
      idcardImg2: [],
      yuangongList: [],
      qufuTree: [],
      qufuProps: {
        value: "id",
        label: "fieldName",
        children: "childGameAttributes",
        expandTrigger: "hover",
      },
      isBaopei: false,

      type: [
        {
          name: "收入",
          value: 1,
        },
        {
          name: "支出",
          value: 2,
        },
      ],
      billTypeList: [],
      billTypeConfig: null, //自定义字段配置
      title: "创建回收单",
      isEdit: false,
      uploadImgUrl: "",
      imgShowList: [],
      newImages: [],
      imgFileList: [],
      form: {
        gameId: "",
        qufuIds: "",
        accountNumber: "",
        accountPassword: "",
        securityPhone: "",
        price: "",
        backAmount: "",
        guaranteeAmount: "",
        buyerId: "",
        guaranteeTenantName: "",
        channel: "",
        sellerName: "",
        buyerPayStatus: "",
        changeBindState: "",
        guaranteePayStatus: "",
        shoukuanfang: "",
        shoukuanzhanghao: "",
        name: "",
        idCard: "",
        phoneNumber: "",
        adress: "",
        emblemIdcardImg: "",
        faceIdcardImg: "",
        remark: "",
        otherNo: "",
        sellerPhone: "",
        secondImg: "",
        walletImg: "",
        buyerImg: "",
        buyerActualAmount: "",
        telid: "",
        goodsId: "",
        onState: "",
        goodsContent: "",
      },
      headers: {},
      rules: {
        gameId: [{ required: true, message: "请选择游戏", trigger: "change" }],
        qufuIds: [{ required: true, message: "请选择区服", trigger: "change" }],
        accountNumber: [
          { required: true, message: "请输入游戏账号", trigger: "change" },
        ],
        accountPassword: [
          { required: true, message: "请输入游戏密码", trigger: "change" },
        ],
        securityPhone: [
          { required: true, message: "请选择手机号", trigger: "change" },
          { validator: phoneCheck, trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入价格", trigger: "change" },
          { validator: priceRule, trigger: "change" },
        ],
        backAmount: [
          { required: true, message: "请输入回收价", trigger: "change" },
          { validator: priceRule, trigger: "change" },
        ],
        // guaranteeAmount: [
        //   { required: true, message: "请输入游戏账号", trigger: "change" },
        //   { validator: priceRule, trigger: "change" },
        // ],
        buyerId: [{ required: true, message: "请选择", trigger: "change" }],
        guaranteeTenantName: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        channel: [{ required: true, message: "请选择", trigger: "change" }],
        // sellerName: [{ required: true, message: "请填写", trigger: "change" }],
        buyerId: [{ required: true, message: "请选择", trigger: "change" }],
        buyerPayStatus: [
          { required: true, message: "请选择", trigger: "change" },
        ],
        // changeBindState: [
        //   { required: true, message: "请选择", trigger: "change" },
        // ],
        // guaranteePayStatus: [
        //   { required: true, message: "请选择", trigger: "change" },
        // ],
        // shoukuanfang: [
        //   { required: true, message: "请填写", trigger: "change" },
        // ],
        // shoukuanzhanghao: [
        //   { required: true, message: "请填写", trigger: "change" },
        // ],

        name: [{ required: true, message: "请填写", trigger: "change" }],
        idCard: [
          { required: true, message: "请填写", trigger: "change" },
          { validator: idCardRule, trigger: "change" },
        ],
        phoneNumber: [
          { required: true, message: "请填写", trigger: "change" },
          { validator: phoneCheck, trigger: "change" },
        ],
        adress: [{ required: true, message: "请填写", trigger: "change" }],
        
      },
    };
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    },
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  methods: {
      fillIn() {
      this.$refs.huishouFillInRef.init()
    },
      // 处理快速填充的数据
    handleFillData(data) {
        // 填充基本字段
        Object.keys(data).forEach(key => {
            if (this.form.hasOwnProperty(key)) {
                this.form[key] = data[key];
            }
        });
        
        // 处理游戏名称特殊逻辑（需要匹配gameId）
        if (data.gameName && this.gameList.length) {
            const game = this.gameList.find(item => item.name === data.gameName);
            if (game) {
                this.form.gameId = game.id;
                this.gameChange(game.id); // 触发游戏改变事件，加载对应区服
            }
        }
        if (data.buyerName && this.yuangongList.length) {
            const user = this.yuangongList.find(item => item.nickName === data.buyerName);
            if (user) {
                this.form.buyerId = user.userId;
                this.buyerChange(user.userId); // 触发回收人改变事件
            }
        }
        // 如果填写了回收价和包赔费，重新计算应付金额
        if (data.backAmount || data.guaranteeAmount) {
            this.computedBuyerActualAmount();
        }
        this.$forceUpdate();
        this.$message.success('数据填充成功');
    },
    // 打开弹窗
    open(flag, id) {
      // console.log("%c Line:265 🥃 id", "color:#3f7cff", id);
      this.isBaopei = false;

      this.newImages = [];
      this.imgShowList = [];
      this.imgFileList = [];
      this.dialogVisible = true;
      this.title = "创建回收单";
      this.isEdit = false;
      this.form = {
        gameId: "",
        qufuIds: "",
        accountNumber: "",
        accountPassword: "",
        securityPhone: "",
        price: "",
        backAmount: "",
        guaranteeAmount: "",
        buyerId: "",
        guaranteeTenantName: "",
        channel: "",
        sellerName: "",
        buyerPayStatus: "",
        changeBindState: "",
        guaranteePayStatus: "",
        shoukuanfang: "",
        shoukuanzhanghao: "",
        name: "",
        idCard: "",
        phoneNumber: "",
        adress: "",
        emblemIdcardImg: "",
        faceIdcardImg: "",
        remark: "",
        otherNo: "",
        sellerPhone: "",
        secondImg: "",
        walletImg: "",
        buyerImg: "",
        buyerActualAmount: "",
        telid: "",
        goodsId: "",
        onState: "",
        goodsContent: "",
      };
      if (flag == "edit") {
        this.title = "修改回收单";
        this.isEdit = true;
        this.handleUpdate(id);
      }
      if (flag == "byGoods") {
        this.goodsInfoSet(id);
      }
      this.getYuangongList(flag);
      this.getGameList();
    },
    // 奇特图片扫码上传
    saomaEnd(e) {
      if (e && e.length) {
        this.imgFileList = this.imgFileList.concat(e);
        this.imgShowList = this.imgShowList.concat(e);
      }
    },
    // 回显商品自带属性
    goodsInfoSet(goods) {
      const goodsInfo = JSON.parse(JSON.stringify(goods));
      // 获取区服
      if (goodsInfo.gameId) {
        this.getQufuTree(goodsInfo.gameId);
      }
      // 处理区服
      const qufuIds = [];
      // 赋值当前选择的游戏
      this.currentGame = {
        type: goodsInfo.gameType,
        name: goodsInfo.gameName,
        id: goodsInfo.gameId,
      };
      if (goodsInfo.systemId) {
        qufuIds.push(goodsInfo.systemId);
      }
      if (goodsInfo.carrierId) {
        qufuIds.push(goodsInfo.carrierId);
      }
      if (goodsInfo.groupId) {
        qufuIds.push(goodsInfo.groupId);
      }
      if (goodsInfo.serverId) {
        qufuIds.push(goodsInfo.serverId);
      }
      this.form.qufuIds = [...qufuIds];
      this.form.price = goodsInfo.price;
      this.form.gameName = goodsInfo.gameName;
      this.form.gameId = goodsInfo.gameId;
      this.form.goodsId = goodsInfo.id;
      this.form.onState = 2;
      this.form.accountNumber = goodsInfo.accountNumber;
      this.form.accountPassword = goodsInfo.accountPassword;
      this.form.securityPhone = goodsInfo.securityPhone;
      this.form.backAmount = goodsInfo.costPrice || null;
      this.form.telid = goodsInfo.telid;

      this.form.buyerImg = goodsInfo.dakuanImg;
      this.form.walletImg = goodsInfo.walletImg;
      this.form.secondImg = goodsInfo.secondImg;
      if (goodsInfo.otherImg) {
        this.imgShowList = JSON.parse(goodsInfo.otherImg);
        this.imgFileList = JSON.parse(goodsInfo.otherImg);
      }
    },

    // 重置
    reset() {
      // this.form = {
      //   type: "",
      //   bookType: "",
      //   duifangmingcheng: "",
      //   duifangzhanghu: "",
      //   benfangmingcheng: "",
      //   benfangzhanghu: "",
      //   jine: "",
      //   jingbanren: "",
      //   fuheren: "",
      //   mingxi: "",
      //   beizhu: "",
      //   img: "",
      // };
      this.currentGame = "";
      this.qufuTree = [];
      this.form.id = null;
      this.form.buyerActualAmount = "";
      this.$refs.form.resetFields();
    },
    // 获取区服树结构
    getQufuTree(gameId) {
      this.qufuTree = [];
      let obj = {};
      obj.gameId = gameId || this.form.gameId;
      gameListApi.qufuTreeGetByGameId(obj).then((res) => {
        this.qufuTree = [...res.data];
      });
    },
    // 获取所有员工列表
    getYuangongList(flag) {
      console.log("%c Line:567 🍕 flag", "color:#f5ce50", flag);
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
          if (
            (flag == "add" || !flag) &&
            this.userInfo &&
            this.userInfo.userId &&
            this.yuangongList.length
          ) {
            this.buyerChange(this.userInfo.userId);
          }
        });
    },
    // 游戏列表
    async getGameList() {
      let res = await gameListApi.getCustomGamelist();
      // ////console.log("%c Line:278 🍫 res", "color:#465975", res);
      this.gameList = res.data;
      if (this.gameList && this.gameList.length) {
      } else {
        this.gameList = this.allGameList;
      }
    },
    // 游戏选择改变
    gameChange(e) {
      if (this.form.qufu) {
        this.form.qufu = "";
      }
      this.currentGame = "";
      this.form.gameName = "";
      if (e) {
        this.getQufuTree();
        for (let i = 0; i < this.gameList.length; i++) {
          if (this.gameList[i].id == e) {
            this.form.gameName = this.gameList[i].name;
            this.currentGame = this.gameList[i];
          }
        }
        if(this.currentGame.carrierType==2){
          // 网易 设置图片非必填
          delete this.rules.secondImg
          delete this.rules.buyerImg
        }else if(this.currentGame.carrierType==1){
          // 腾讯
          this.rules.secondImg = [{ required: true, message: "请上传", trigger: "blur" }]
          this.rules.buyerImg = [{ required: true, message: "请上传", trigger: "blur" }]
        }else{
          // 其他游戏 只必填订单截图 不必填二次截图
          delete this.rules.secondImg
          this.rules.buyerImg = [{ required: true, message: "请上传", trigger: "blur" }]
        }
        this.rules = JSON.parse(JSON.stringify(this.rules))
        // this.resetFields('form')
        this.$nextTick(()=>{
          this.$refs.form.clearValidate()
        })

      }
    },
    // 回收人 改变
    buyerChange(e) {
      if (e) {
        for (let i = 0; i < this.yuangongList.length; i++) {
          if (this.yuangongList[i].userId == e) {
            this.form.buyerName = this.yuangongList[i].nickName;
            this.form.buyerId = this.yuangongList[i].userId;
          }
        }
      } else {
        this.form.buyerName = "";
        this.form.buyerId = "";
      }
    },
    // 区服改变
    qufuChange(e) {},
    // 价格改变  计算应付金额
    computedBuyerActualAmount() {
      const guaranteeAmount = Number(this.form.guaranteeAmount || 0);
      if (this.form.backAmount) {
        const total = Number(this.form.backAmount) + guaranteeAmount;
        this.form.buyerActualAmount = Math.round(total * 100) / 100;
        this.$forceUpdate();
      }
    },
    /**选择相关  start*/

    // 打开选择手机弹窗
    openSelectPhone() {
      if (this.form.gameId) {
        this.$refs.selectPhone.open(this.currentGame);
      } else {
        this.$message.error("请先选择游戏");
      }
    },
    // 选择绑定手机
    getSelectPhone(item) {
      if (item.zulinfangId) {
        // 租用的卡位
        this.form.isMyTel = 2;
        this.form.telid = item.telManageId;
        this.form.securityPhone = item.tel ? item.tel : "";
      } else {
        // 我的卡位
        this.form.telid = item.id;
        this.form.isMyTel = 1;
        this.form.securityPhone = item.tel ? item.tel : "";
      }
      this.$forceUpdate();
    },

    // 取消绑定手机
    delPhone(type) {
      if (type == "phone") {
        this.form.telid = "";
        this.form.isMyTel = "";
        this.form.securityPhone = "";
      } else if (type == "guaranteeTenantName") {
        this.form.guaranteeTenantName = "";
      } else if (type == "channel") {
        this.form.channel = "";
      }

      this.$forceUpdate();
    },
    // 打开渠道哦选择
    openSelectQudao(type) {
      this.$refs.qudaoDialog.open(type);
    },
    // 渠道选择完成
    getSelectQudao(item) {
      if (item.type == 1) {
        // 包赔商
        this.form.guaranteeTenantName = item.name;
      } else if (item.type == 2) {
        // 平台渠道
        this.form.channel = item.name;
      }
      this.$forceUpdate();
    },
    /**选择相关  end*/

    // 单张图片上传成功
    uploadSucccess(e, key) {
      this.form[key] = e;
    },
    // 获取账单类型列表
    getTypeList() {
      jizhangbenApi.getTypeList().then((res) => {
        this.billTypeList = res.rows;

        if (res.rows.length == 0) {
          this.$message.error("请先配置账单类型！");
        }
      });
    },

    /** 查询详情进行回显 */
    handleUpdate(id) {
      onSelfApi.getBackClueOrderInfo(id).then((res) => {
        let form = { ...res.data };
        if (form.otherImg) {
          const arr = JSON.parse(form.otherImg);
          if (arr.length) {
            this.imgShowList = arr;
            this.imgFileList = JSON.parse(JSON.stringify(arr));
          }
        }
        // 获取区服
        if (form.gameId) {
          this.getQufuTree(form.gameId);
        }

        // 处理区服
        const qufuIds = [];
        const goodsInfo = JSON.parse(form.goodsContent);
        console.log("%c Line:683 🍌 goodsInfo", "color:#465975", goodsInfo);
        // 赋值当前选择的游戏
        this.currentGame = {
          type: goodsInfo.gameType,
          name: goodsInfo.gameName,
          id: goodsInfo.gameId,
        };
        form.price = goodsInfo.price;
        if (goodsInfo.systemId) {
          qufuIds.push(goodsInfo.systemId);
        }
        if (goodsInfo.carrierId) {
          qufuIds.push(goodsInfo.carrierId);
        }
        if (goodsInfo.groupId) {
          qufuIds.push(goodsInfo.groupId);
        }
        if (goodsInfo.serverId) {
          qufuIds.push(goodsInfo.serverId);
        }
        form.qufuIds = [...qufuIds];

        // 处理收款信息
        if (form.guaranteeTenantCollection) {
          const obj = JSON.parse(form.guaranteeTenantCollection);
          form.shoukuanfang = obj.collectionUserName;
          form.shoukuanzhanghao = obj.collectionAccount;
        }
        // 处理包赔信息
        if (form.guaranteeInfo) {
          this.isBaopei = true;
          const obj = JSON.parse(form.guaranteeInfo);
          form = { ...form, ...obj };
        }
        form.telid = goodsInfo.telid;
        form.isMyTel = goodsInfo.isMyTel;
        this.form = { ...form };
        this.$forceUpdate();
      });
    },
    submitForm(formName) {
      this.$refs["" + formName].validate((valid) => {
        if (valid) {
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
            let newArr = [];
            this.newImages.forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            this.form.otherImg = JSON.stringify(
              this.imgFileList.concat(newArr)
            );
          } else {
            this.form.otherImg = JSON.stringify(this.imgFileList);
          }
          // 处理包赔信息
          if (this.isBaopei) {
            let baopeiInfo = {
              name: this.form.name,
              phoneNumber: this.form.phoneNumber,
              idCard: this.form.idCard,
              adress: this.form.adress,
              otherRemark: this.form.otherRemark || "",
              faceIdcardImg: this.form.faceIdcardImg || "",
              emblemIdcardImg: this.form.emblemIdcardImg || "",
            };
            this.form.guaranteeInfo = JSON.stringify(baopeiInfo);
          }

          // 处理收款信息
          let guaranteeTenantCollection = {
            collectionUserName: this.form.shoukuanfang,
            collectionAccount: this.form.shoukuanzhanghao,
            collectionAccountName: " ",
          };
          this.form.guaranteeTenantCollection = JSON.stringify(
            guaranteeTenantCollection
          );
          // 处理商品信息
          let goodsInfo = {};
          // 处理区服
          let qufu = "";
          if (this.currentGame.type == 1) {
            // 端游
            this.qufuTree.forEach((daqu) => {
              if (daqu.id == this.form.qufuIds[0]) {
                qufu += daqu.fieldName;
                goodsInfo.groupId = daqu.id;
                goodsInfo.groupName = daqu.fieldName;
                if (
                  daqu.childGameAttributes &&
                  daqu.childGameAttributes.length
                ) {
                  daqu.childGameAttributes.forEach((fu) => {
                    if (fu.id == this.form.qufuIds[1]) {
                      qufu += fu.fieldName;
                      goodsInfo.serverId = fu.id;
                      goodsInfo.serverName = fu.fieldName;
                    }
                  });
                }
              }
            });
          } else {
            // 手游
            this.qufuTree.forEach((sys) => {
              if (sys.id == this.form.qufuIds[0]) {
                qufu += sys.fieldName;
                goodsInfo.systemId = sys.id;
                goodsInfo.systemName = sys.fieldName;
                if (sys.childGameAttributes && sys.childGameAttributes.length) {
                  sys.childGameAttributes.forEach((carr) => {
                    if (carr.id == this.form.qufuIds[1]) {
                      qufu += carr.fieldName;
                      goodsInfo.carrierId = carr.id;
                      goodsInfo.carrierName = carr.fieldName;
                      if (
                        carr.childGameAttributes &&
                        carr.childGameAttributes.length
                      ) {
                        carr.childGameAttributes.forEach((daqu) => {
                          if (daqu.id == this.form.qufuIds[2]) {
                            qufu += daqu.fieldName;
                            goodsInfo.groupId = daqu.id;
                            goodsInfo.groupName = daqu.fieldName;
                            if (
                              daqu.childGameAttributes &&
                              daqu.childGameAttributes.length
                            ) {
                              daqu.childGameAttributes.forEach((fu) => {
                                if (fu.id == this.form.qufuIds[3]) {
                                  qufu += fu.fieldName;
                                  goodsInfo.serverId = fu.id;
                                  goodsInfo.serverName = fu.fieldName;
                                }
                              });
                            }
                          }
                        });
                      }
                    }
                  });
                }
              }
            });
          }
          this.form.qufu = qufu;
          goodsInfo.gameId = this.form.gameId;
          goodsInfo.gameName = this.form.gameName;
          goodsInfo.gameType = this.currentGame.type;
          goodsInfo.accountNumber = this.form.accountNumber;
          goodsInfo.accountPassword = this.form.accountPassword;
          goodsInfo.securityPhone = this.form.securityPhone;
          goodsInfo.isMyTel = this.form.isMyTel;
          goodsInfo.telid = this.form.telid;
          goodsInfo.price = this.form.price;
          goodsInfo.costPrice = this.form.buyerActualAmount;
          goodsInfo.importantRemark = this.form.remark;
          goodsInfo.dakuanImg = this.form.buyerImg;
          // const otherImg = []
          if (this.form.secondImg) {
            goodsInfo.secondImg = this.form.secondImg;
          }
          if (this.form.walletImg) {
            goodsInfo.walletImg = this.form.walletImg;
          }
          goodsInfo.otherImg = this.form.otherImg;
          this.form.goodsContent = JSON.stringify(goodsInfo);

          if(!this.form.buyerActualAmount){
            this.computedBuyerActualAmount()
          }
          if (this.isEdit) {
            // // 编辑
            onSelfApi.backClueOrderEditSelf(this.form).then((res) => {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.$parent.getList();
            });

            // jizhangbenApi.editTallyBook(this.form).then((res) => {
            //   this.$message.success(res.msg);
            //   this.dialogVisible = false;
            //   this.$parent.search();
            // });
          } else {
            // 新增
            // console.log(this.form);
            onSelfApi.backClueOrderCreateSelf(this.form).then((res) => {
              this.$message.success(res.msg);
              this.$emit("addSuccess");
              this.dialogVisible = false;
              // this.$parent.getList();
            });
            // jizhangbenApi.addTallyBook(this.form).then((res) => {
            //   this.$message.success(res.msg);
            //   this.dialogVisible = false;
            //   this.$parent.search();
            // });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },
    close() {
      this.dialogVisible = false;
    },

    // 身份证图片相关---start----
    emblemIdcardImgChange(e) {
      this.form.emblemIdcardImg = e;
    },
    faceIdcardImgChange(e) {
      this.form.faceIdcardImg = e;
    },
    // // 身份证国徽面移除
    // handleAvatarRemove1(response, file) {
    //   this.form.emblemIdcardImg = "";
    //   this.idcardImg1 = [];
    // },
    // // 身份证国徽面上传成功
    // handleAvatarSuccess1(res, file) {
    //   if (res.code == 200) {
    //     this.form.emblemIdcardImg = res.data.filePath;
    //   }
    // },
    // // 身份证人像面面图片移除
    // handleAvatarRemove2(response, file) {
    //   this.form.faceIdcardImg = "";
    //   this.idcardImg2 = [];
    // },
    // // 身份证人像面片上传成功
    // handleAvatarSuccess2(res, file) {
    //   if (res.code == 200) {
    //     this.form.faceIdcardImg = res.data.filePath;
    //   }
    // },
    // 身份证图片相关---end----
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

/* /deep/ .el-upload-dragger {
  width: 150px;
  height: 150px;
} */

::v-deep .upload_img_box .el-form-item {
  width: 250px;
}
/* /deep/ .el-upload-list__item-progress,
/deep/ .el-icon-loading {
  display: none;
} */
.phone-box .name {
  white-space: nowrap;
  width: 97px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
